package jh.com.jhappbf.unload;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class UnloadConfirmActivity extends AbActivity implements OnClickListener {

    private ImageView mSearchImg;
    private ImageView mSelectPlatenumImg;
    private EditText mPlateNumEdit;

    private TextView mDetailContentTxt;

    private LinearLayout mInputAreaLayout;
    private EditText mBucketCountEdit;
    private EditText mBucketWeightEdit;
    private EditText mBagCountEdit;
    private EditText mBagWeightEdit;
    private EditText mMemoEdit;
    private EditText mAddressEdit;

    private LinearLayout mBucketCountLayout;
    private LinearLayout mBagCountLayout;
    private ImageView mAddressSelectImg;
    private Button mConfirmBtn;
    private Button mRefreshBtn;
    private AbDialogFragment mDialogFragment;
    private final int REQUESTCODE = 0X001;
    private final int REQUESTCODEADDRESS = 0X002;
    private String mSaverId = "";
    private String mTransport = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.unload_confirm_activity);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.unload_confirm_title);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 初始化
     */
    private void initView() {
        mSearchImg = findViewById(R.id.unload_search_img);
        mSelectPlatenumImg = findViewById(R.id.unload_search_platenum);
        mSelectPlatenumImg.setOnClickListener(this);
        mSearchImg.setOnClickListener(this);
        mPlateNumEdit = findViewById(R.id.unload_search_edit);
        mDetailContentTxt = findViewById(R.id.unload_content_detail);
        mInputAreaLayout = findViewById(R.id.unload_input_area);

        mBucketCountEdit = findViewById(R.id.unload_bucket_count_edit);
        mBucketWeightEdit = findViewById(R.id.unload_bucket_weight_edit);
        mBucketCountLayout = findViewById(R.id.unload_bucket_count_layout);

        mBagCountEdit = findViewById(R.id.unload_count_edit);
        mBagWeightEdit = findViewById(R.id.unload_weight_edit);
        mBagCountLayout = findViewById(R.id.unload_bag_count_layout);


        mAddressEdit = findViewById(R.id.unload_address_edit);
        mAddressSelectImg = findViewById(R.id.unload_address_select_img);
        mAddressSelectImg.setOnClickListener(this);
        mMemoEdit = findViewById(R.id.unload_memo_edit);

        mConfirmBtn = findViewById(R.id.unload_btn_ok);
        mConfirmBtn.setOnClickListener(this);
        mRefreshBtn = findViewById(R.id.unload_btn_refresh);
        mRefreshBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.unload_search_img:
                getData();
                break;
            case R.id.unload_search_platenum:
                Intent i = new Intent(UnloadConfirmActivity.this, UnloadPlatenumSelect.class);
                startActivityForResult(i, REQUESTCODE);
                break;
            case R.id.unload_address_select_img:
                Intent intent = new Intent(UnloadConfirmActivity.this, GetAddress.class);
                startActivityForResult(intent, REQUESTCODEADDRESS);
                break;
            case R.id.unload_btn_ok:
                confirmUnload();
                break;
            case R.id.unload_btn_refresh:
                refresh();
                break;
            default:
                break;
        }
    }

    /**
     * 查询称重数据
     */
    private void getData() {
        String plateNumber = String.valueOf(mPlateNumEdit.getText());
        if (TextUtils.isEmpty(plateNumber)) {
            AbToastUtil.showToast(UnloadConfirmActivity.this, "车号不能为空,查询失败!");
            return;
        }
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "数据查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        String methodName = "getWeightByPlatenum";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("platenum");
        value.add(plateNumber);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UnloadConfirmActivity.this);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null && data.size() > 0) {
                JSONObject obj = data.get(0);
                String result = obj.optString("result");
                String memo = obj.optString("memo");
                String transport = obj.optString("transport");
                mTransport = transport;
                mSaverId = obj.optString("id");
                switch (transport) {
                    case "桶装":
                        mBucketCountLayout.setVisibility(View.VISIBLE);
                        mBagCountLayout.setVisibility(View.GONE);
                        break;
                    case "袋装":
                        mBucketCountLayout.setVisibility(View.GONE);
                        mBagCountLayout.setVisibility(View.VISIBLE);
                        break;
                    default:
                        mBucketCountLayout.setVisibility(View.GONE);
                        mBagCountLayout.setVisibility(View.GONE);
                        break;
                }
                if ("true".equals(result)) {
                    mDetailContentTxt.setText(memo);
                } else {
                    AbToastUtil.showToast(UnloadConfirmActivity.this, memo);
                }
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UnloadConfirmActivity.this);
            AbToastUtil.showToast(UnloadConfirmActivity.this, "查询失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    /**
     * 确认卸货
     */
    private void confirmUnload() {
        String bucketCount = mBucketCountEdit.getText().toString();
        String bucketWeight = mBucketWeightEdit.getText().toString();
        String bagCount = mBagCountEdit.getText().toString();
        String bagWeight = mBagWeightEdit.getText().toString();
        String address = mAddressEdit.getText().toString();
        String memo = mMemoEdit.getText().toString();
        if (address.length() == 0) {
            AbToastUtil.showToast(this, "卸货地址不能为空!");
            return;
        }

        switch (mTransport) {
            case "桶装":
                if (bucketCount.length() == 0) {
                    AbToastUtil.showToast(this, "桶数不能为空!");
                    return;
                }

                if ("0".equals(bucketCount)) {
                    AbToastUtil.showToast(this, "桶数不能为0!");
                    return;
                }

                if (bucketWeight.length() == 0) {
                    AbToastUtil.showToast(this, "桶皮不能为空!");
                    return;
                }
                break;
            case "袋装":
                if (bagCount.length() == 0) {
                    AbToastUtil.showToast(this, "袋数不能为空!");
                    return;
                }

                if ("0".equals(bagCount)) {
                    AbToastUtil.showToast(this, "袋数不能为0!");
                    return;
                }

                if (bagWeight.length() == 0) {
                    AbToastUtil.showToast(this, "袋皮不能为空!");
                    return;
                }
                break;
            default:
                bucketCount = "0";
                bucketWeight = "0";
                bagCount = "0";
                bagWeight = "0";
                break;
        }

        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "数据查询中,请稍等...");
        mDialogFragment.setCancelable(false);

        String methodName = "addUnloadConfirm";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        param.add("address");
        param.add("user");
        param.add("bucketCount");
        param.add("bucketWeight");
        param.add("bagCount");
        param.add("bagWeight");
        param.add("memo");

        value.add(mSaverId);
        value.add(address);
        value.add(State.mName);
        value.add(bucketCount);
        value.add(bucketWeight);
        value.add(bagCount);
        value.add(bagWeight);
        value.add(memo);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(UnloadConfirmActivity.this);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null) {
                JSONObject obj = data.get(0);
                String result = obj.optString("result");
                if (result.length() == 0) {
                    result = "确认失败!";
                }
                if (result.contains("成功")) {
                    refresh();
                }
                AbToastUtil.showToast(UnloadConfirmActivity.this, result);
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(UnloadConfirmActivity.this);
            AbToastUtil.showToast(UnloadConfirmActivity.this, "查询失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    /**
     * 刷新
     */
    private void refresh() {
        mDetailContentTxt.setText("");
        mPlateNumEdit.setText("");
        mBucketCountEdit.setText("");
        mBagCountEdit.setText("");
        mMemoEdit.setText("");
        mAddressEdit.setText("");

        mBucketCountLayout.setVisibility(View.GONE);
        mBagCountLayout.setVisibility(View.GONE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String value = data.getStringExtra("result");
            if (requestCode == REQUESTCODE) {
                mPlateNumEdit.setText(value);
                if (TextUtils.isEmpty(value)) {
                    return;
                }
                if (value.length() > 0) {
                    getData();
                }
            } else if (requestCode == REQUESTCODEADDRESS) {
                mAddressEdit.setText(value);

            }
        }
    }
}
